package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.FacilityDTO;
import business.FacilityManager;

public class UpdateFacilityServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public UpdateFacilityServlet()
	{
		super();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	} 
	
	/**
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FacilityManager fm = new FacilityManager();
		FacilityDTO facility = new FacilityDTO();
				
		Map<String, String> errors = new HashMap<String, String>();
		
		String origin = request.getParameter("facilityname");
		String origin2 = request.getParameter("description");
		String origin3 = request.getParameter("capacity");
		
		if (origin.isEmpty()) {
			errors.put("origin", "Enter Facility Name");
		}else
		{
			errors.remove("origin");
		}
		if (origin2.isEmpty()) {
			errors.put("origin2", "Enter Description");
		}else
		{
			errors.remove("origin2");
		}
		if ((origin3.isEmpty())||!(origin3.matches("\\d+"))) {
			errors.put("origin3", "Enter only Number");
		}else
		{
			errors.remove("origin3");
		}
			if (errors.isEmpty()) {
				facility.setFacilityID(Integer.parseInt(request.getParameter("facilityID")));
				facility.setFacilityName(request.getParameter("facilityname"));
				facility.setDescription(request.getParameter("description"));
				facility.setFacilityType(request.getParameter("type"));
				facility.setCapacity(request.getParameter("capacity"));
				fm.updateFacility(facility);
				ArrayList<FacilityDTO> data = fm.findAllFacility();
				request.setAttribute("facilities", data);
				RequestDispatcher rd = request.getRequestDispatcher("Facility.jsp");
			try {
				rd.forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		} else {
			request.setAttribute("errors", errors);
			request.setAttribute("type", request.getParameter("type"));
	        request.getRequestDispatcher("UpdateFacility.jsp").forward(request, response);
	       
		}
}
}